package com.wfs.interceptors;

import com.wfs.utils.JwtUtil;
import com.wfs.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        // 获取请求头中的Authorization字段
        String token = request.getHeader("Authorization");
        log.info("token:{}",token);
        try{
            // 解析token
            Map<String, Object> map = JwtUtil.parseToken(token);
            log.info("map:{}",map);
            ThreadLocalUtil.set(map);
        }catch (Exception e){
            // 如果解析失败，设置响应状态码为401，表示未授权
            log.info("未授权");
            response.setStatus(401);
            return false;
        }
        // 如果解析成功，返回true
        log.info("解析成功");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
        // 清除ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
